<template>
  <vxe-grid
    ref="xTable"
    v-loading="loading"
    highlight-hover-row
    highlight-current-row
    row-key
    class="sortable-tree"
    :data="tableData"
    v-bind="$attrs"
    v-on="$listeners"
    @cell-click="cellClick"
  >
    <vxe-table-column
      v-for="(item, k) in tableColumn"
      :key="k"
      :title="item.title"
      :field="item.field"
      :tree-node="item.treeNode"
      :width="item.width"
      :show-overflow="item.showOverflow"
    >
      <template v-slot="{ row }">
        <template v-if="item.field === 'icon'">
          <el-dropdown
            placement="bottom"
            size="mini"
            trigger="click"
            @command="handleDropdown($event, row)"
            @visible-change="dropdownVisibleChange"
          >
            <span class="el-dropdown-link">
              <i class="iconfont iconicon_more mr-2"></i>
            </span>
            <el-dropdown-menu
              slot="dropdown"
              style="min-width: 80px;"
            >
              <el-dropdown-item
                v-for="(subItem, s_k) in dropdownList"
                :key="s_k"
                :command="subItem.value"
                class="dropdown-item"
                @mouseenter.native="onMouseHover(s_k, true)"
                @mouseleave.native="onMouseHover(s_k, false)"
              >
                {{ subItem.label }}
                <i v-if="subItem.children" class="el-icon-arrow-right icon"></i>
                <template v-if="subItem.children && subItem.visible">
                  <ul class="download-right" style="min-width: 70px;">
                    <li
                      v-for="(childItem, c_k) in subItem.children"
                      :key="c_k"
                      class="el-dropdown-menu__item"
                      @click="handleDropdown(childItem.value, row)"
                    >{{ childItem.label }}</li>
                  </ul>
                </template>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

        </template>
        <template v-if="item.treeNode">
          <i class="iconfont" :class="row[children] ? 'iconlifangtilitiduomiantifangkuai': 'iconicon_material'"></i>
          {{ row[item.field] }}
        </template>
        <template v-else>{{ row[item.field] }}</template>
      </template>
    </vxe-table-column>
  </vxe-grid>
</template>
<script>
import Sortable from 'sortablejs'
import XEUtils from 'xe-utils'

export default {
  name: 'SortTable',
  components: {},
  props: {
    dropdownList: {
      type: Array,
      default: () => []
    },
    tableData: {
      type: Array,
      default: () => []
    },
    tableColumn: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    // 字节点字段名称
    children: {
      type: String,
      default: 'children'
    }
  },
  data() {
    return {
      isDropdownMenu: true,
      sttimer: null
    }
  },
  watch: {
  },
  created() {
  },
  mounted() {
    document.body.ondrop = function(event) {
      event.preventDefault()
      event.stopPropagation()
    }
    this.treeDrop()
  },
  methods: {
    // 点击描述列触发
    cellClick(val) {
      if (this.$refs.xTable.getCurrentRecord()) {
        this.$emit('cellClick', this.$refs.xTable.getCurrentRecord())
      }
    },
    handleDropdown(type, row) {
      this.$emit('handleDropdown', type, row)
    },
    treeDrop() {
      const xTable = this.$refs.xTable
      const tbody = xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody')
      Sortable.create(tbody, {
        fallbackOnBody: true,
        group: {
          name: 'name', // 相同名称可以拖拽
          pull: 'clone', // 克隆
          put: false // 禁止被移入
        },
        animation: 150,
        onEnd: ({ item, oldIndex }) => {
          const options = { children: this.children }
          const targetTrElem = item
          const wrapperElem = targetTrElem.parentNode
          const prevTrElem = targetTrElem.previousElementSibling
          const tableData = this.tableData
          const selfRow = xTable.getRowNode(targetTrElem).item
          const selfNode = XEUtils.findTree(tableData, row => row === selfRow, options)
          let prevParent = null
          if (prevTrElem) {
            // 判断是否移动到其他列表
            if (!xTable.getRowNode(prevTrElem)) {
              return
            }
            // 移动位置的上一条数据
            const prevRow = xTable.getRowNode(prevTrElem).item
            const prevNode = XEUtils.findTree(tableData, row => row === prevRow, options)
            prevParent = prevNode.parent
            if (XEUtils.findTree(selfRow[options.children], row => prevRow === row, options)) {
              // 错误的移动
              const oldTrElem = wrapperElem.children[oldIndex]
              wrapperElem.insertBefore(targetTrElem, oldTrElem)
              return this.$XModal.message({ message: '不允许自己给自己拖动！', status: 'error' })
            }
            const currRow = selfNode.items.splice(selfNode.index, 1)[0]
            // (prevRow.children && prevRow.children.length === 0) 当字节点为空的时候
            if (
              xTable.isTreeExpandByRow(prevRow) ||
              (prevRow.children && prevRow.children.length === 0)
            ) {
              // 移动到当前的子节点
              prevRow[options.children].splice(0, 0, currRow)
            } else {
              // 移动到相邻节点
              prevNode.items.splice(prevNode.index + (selfNode.index < prevNode.index ? 0 : 1), 0, currRow)
            }
          } else {
            // 移动到第一行
            var currRow = selfNode.items.splice(selfNode.index, 1)[0]
            tableData.unshift(currRow)
          }
          // 如果变动了树层级，需要刷新数据
          xTable.syncData()
          // 数据排序发生改变触发
          this.$nextTick(() => {
            let newVal = null
            if (prevParent === null) {
              tableData.map(item => {
                if (item._XID === selfRow._XID) {
                  newVal = null
                } else if (item.children && item.children.length && item.children[0]._XID === selfRow._XID) {
                  newVal = item
                }
              })
            } else {
              prevParent.children.map(item => {
                if (item._XID === selfRow._XID) {
                  newVal = prevParent
                } else if (item.children && item.children.length && item.children[0]._XID === selfRow._XID) {
                  newVal = item
                }
              })
            }
            // 最外层上下排序，拖动触发不作处理
            if (newVal === null && selfNode.parent === null) {
              return
            }
            // 在同一内层上下排序，拖动触发不作处理
            if (newVal && selfNode.parent && newVal._XID === selfNode.parent._XID) {
              return
            }

            console.log(newVal, '新的父节点')
            console.log(selfRow, '自身节点')
            console.log(selfNode.parent, '原本的父节点')

            const newValObj = {
              newParent: newVal,
              oldParent: selfNode.parent,
              selfVal: selfRow,
              tableData: this.tableData
            }
            this.$emit('newResult', newValObj)
          })
        }
      })
    },
    dropdownVisibleChange(flag) {
      if (!flag) {
        const dropdownList = this.dropdownList
        dropdownList.forEach((item, index) => {
          item.visible = false
        })
        this.dropdownList = dropdownList
      }
    },
    onMouseHover(k, type) {
      if (type) {
        this.dropdownList[k].visible = true
      } else {
        this.dropdownList[k].visible = false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.dropdown-item {
  position: relative;
  .download-right {
    padding: 8px 0 !important;
    position: absolute;
    top: -8px;
    right: -80px;
    width: 80px;
    height: auto;
    background-color: #fff !important;
    border-radius: 4px !important;
    box-shadow: 0px 0px 4px 0px rgba(18, 38, 63, 0.17) !important;
  }
  .el-dropdown-menu__item:not(.is-disabled):hover, .el-dropdown-menu__item:focus {
    color: #556ee6 !important;
    background-color: #f2f4ff !important;
  }
}
.iconlifangtilitiduomiantifangkuai {
  color: #DAB46A;
}
::v-deep .vxe-body--row {
  cursor: pointer;
}
</style>
